package com.example.demo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TailLogRunnable implements Runnable {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final String filePath;
    private final WebSocketSession session;

    public TailLogRunnable(String filePath, WebSocketSession session) {
        this.filePath = filePath;
        this.session = session;
    }

    @Override
    public void run() {
        String cmd = "tail -f " + filePath;
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", cmd});
            String charset = System.getProperty("sun.jnu.encoding");
            try (
                    BufferedReader successStream = new BufferedReader(new InputStreamReader(process.getInputStream(), charset))
            ) {
                logger.info("准备读取tail命令结果");
                String successLine;
                while (!Thread.currentThread().isInterrupted() && session.isOpen()) {
                    successLine = successStream.readLine();
                    TextMessage message = new TextMessage(successLine);
                    if (!session.isOpen()) {
                        logger.info("会话已关闭,退出tail - 会话ID: " + session.getId());
                        return;
                    }
                    try {
                        session.sendMessage(message);
                    } catch (Exception e) {
                        logger.info("发送消息失败 - 会话ID: " + session.getId() + ", 错误: " + e.getMessage());
                        e.printStackTrace();
                    }
                }
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
            TextMessage message = new TextMessage(e.getMessage());
            try {
                session.sendMessage(message);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
    }

}
